package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    // 添加好友
    public void save(Long userId, Long friendId) {
        // 1:保存自己的好友数据
        Query query = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        boolean exists = mongoTemplate.exists(query, Friend.class);
        // 先判断好友关系是否存在,如果不存在,再进行保存
        if (!exists){
            Friend friend1 = new Friend();
            friend1.setUserId(userId);
            friend1.setFriendId(friendId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }
        // 2:保存好友的数据,先判断好友关系是否存在
        Query query1 = Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        // 如果不存在,再进行保存
        if (!mongoTemplate.exists(query1,Friend.class)){
            Friend friend2 = new Friend();
            friend2.setUserId(friendId);
            friend2.setFriendId(userId);
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }
    }

    // 分页查询好友列表
    public List<Friend> findByUserId(Long userId, Integer page, Integer pagesize) {
        // 根据id筛选条件
        Criteria criteria = Criteria.where("userId").is(userId);
        // 进行分页查询,并且按照倒叙排序
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Friend.class);
    }
}
